#include <qstring.h>
#include <windows.h>
#include "MidiOutDevice.h"
#include "MidiMessage.h"

MidiOutDevice::MidiOutDevice(void)
{
	_devHandle = NULL;
	_isOpen = false;
}

bool MidiOutDevice::open(int devId)
{
	if (devId < 0 || devId >= getDeviceCount())
		return false;
	
	if (_isOpen)
		close();

	if (midiOutOpen((LPHMIDIOUT)&_devHandle, devId, 
		CALLBACK_NULL, NULL, NULL) != MMSYSERR_NOERROR) 
		return false;

	_isOpen = true;
	return true;
}

void MidiOutDevice::close() 
{
	if (_devHandle && _isOpen) 
		midiOutClose((HMIDIOUT)_devHandle);
	_devHandle = NULL;
	_isOpen = NULL;
}

bool MidiOutDevice::sendMessage(MidiMessage &msg)
{
	MMRESULT mRes = 0;

	if (!_isOpen) 
		return false;

	do {
		mRes = midiOutShortMsg((HMIDIOUT)_devHandle, msg);
	} while (mRes == MIDIERR_NOTREADY);

	return (mRes == MMSYSERR_NOERROR);
}

MidiOutDevice::~MidiOutDevice(void)
{
	close();
}

int MidiOutDevice::getDeviceCount() 
{
	return midiOutGetNumDevs();
}

QString MidiOutDevice::getDeviceName(int devId) 
{
	if (devId >= 0 && devId < getDeviceCount()) {
		MIDIOUTCAPS outputCapabilities;
		midiOutGetDevCaps(devId, &outputCapabilities, sizeof(MIDIOUTCAPS));

		return QString::fromUtf16(outputCapabilities.szPname);
	}

	return QString("Error");
}

int MidiOutDevice::getDeviceByName(QString devName) 
{
	for (int i = 0; i < getDeviceCount(); i++) {
		if (!getDeviceName(i).compare(devName)) {
			return i;
		}
	}

	return -1;
}
